//
//  IndexViewController.m
//  GuoBuGaForIphone
//
//  Created by zhangwo on 16/10/26.
//  Copyright © 2016年 GuoBuGa. All rights reserved.
//

#import "IndexViewController.h"
#import "HomeAddViewController.h"
#import "LoginViewController.h"
#import "PartyViewController.h"

@interface IndexViewController ()
{
    CGFloat contentWidth;
    NSInteger index;
    
    BOOL deleteBtnFlag;
    BOOL vibrateAniFlag;
    UILongPressGestureRecognizer *longPress;
    NSMutableArray *oriData;
    
    ToolBarButton *deleteButton,*cancelButton;
}

@end

@implementation IndexViewController
@synthesize toolbar = _toolbar;

- (void)viewDidLoad {
    [super viewDidLoad];
    
    UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc] init];
    _collectionView = [[UICollectionView alloc] initWithFrame:self.view.bounds collectionViewLayout:layout];
    _collectionView.delegate = self;
    _collectionView.dataSource = self;
    _collectionView.backgroundColor = [UIColor clearColor];
    _collectionView.autoresizingMask = UIViewAutoresizingFlexibleWidth|UIViewAutoresizingFlexibleHeight;//_collectionView的高度
    [self.view addSubview:_collectionView];
    
    longPress = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(changeState:)];
    [_collectionView addGestureRecognizer:longPress];
    
    //设置toolBar半透明
    [self.navigationController.toolbar setTranslucent:YES];
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"登录" style:UIBarButtonItemStylePlain target:self action:@selector(showSign)];
    
    //搜索框
    _searchView = [[HomeSearchView alloc] initWithFrame:CGRectMake(0, 0, SWIDTH-60, 26)];
    _searchView.textField.delegate = self;
    self.navigationItem.titleView = _searchView;
    
    //图片轮播
    layout.headerReferenceSize = CGSizeMake(SWIDTH, 120);
    
    //注册头部视图
    [_collectionView registerClass:[ScrollViewSlider class] forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"headerCell"];
    
    //注册内容视图
    [_collectionView registerClass:[HomeContentViewCell class] forCellWithReuseIdentifier:@"cellItem"];
    
    //内容
    _addDic = @{@"title":@"添加内容",@"image":@"icon-home-add.png",@"id":@"0"};
    NSArray *defaultData = [[NSUserDefaults standardUserDefaults] arrayForKey:@"menuItems"];
    if ([defaultData count] == 0) {
        [[DSXHttpManager sharedManager] GET:@"&c=ad&a=index" parameters:nil progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
            if ([responseObject isKindOfClass:[NSDictionary class]]) {
                if ([[responseObject objectForKey:@"errno"] intValue] == 0) {
                    oriData = [responseObject objectForKey:@"data"];
                    _dataList = [NSMutableArray arrayWithArray:oriData];
                    [_dataList addObject:_addDic];
                    [_collectionView reloadData];
                    [self saveData];
                }
            }
        } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
            NSLog(@"%@",error);
        }];
    }else {
        _dataList = [NSMutableArray arrayWithArray:defaultData];
    }

    //toolBar
    _toolbar = [[UIToolbar alloc] initWithFrame:CGRectMake(0, SHEIGHT-49, SWIDTH, 49)];
    _toolbar.hidden = YES;
    [_toolbar setBackgroundImage:[UIImage imageNamed:@"nav-gbg.png"] forToolbarPosition:UIBarPositionBottom barMetrics:UIBarMetricsDefault];
    
    deleteButton = [[ToolBarButton alloc] initWithFrame:CGRectMake(0, 0, 50, 49)];
    [deleteButton setText:@"删除"];
    [deleteButton setImage:[UIImage imageNamed:@"icon-deletebtn-item.png"]];
    [deleteButton addTarget:self action:@selector(deleteBtn:) forControlEvents:UIControlEventTouchUpInside];
    
    cancelButton = [[ToolBarButton alloc] initWithFrame:CGRectMake(50, 0, 50, 40)];
    [cancelButton setImage:[UIImage imageNamed:@"icon-returnBtn-item.png"]];
    [cancelButton setText:@"取消"];
    [cancelButton addTarget:self action:@selector(cancelBtn:) forControlEvents:UIControlEventTouchUpInside];
    
    UIBarButtonItem *deleteItem,*cancelItem;
    deleteItem = [[UIBarButtonItem alloc] initWithCustomView:deleteButton];
    cancelItem = [[UIBarButtonItem alloc] initWithCustomView:cancelButton];
   
    //使BarButtonItem在toolBar上平均分布
    UIBarButtonItem *flexSpace = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace target:self action:nil];
    [_toolbar setItems:@[flexSpace,deleteItem,flexSpace,cancelItem,flexSpace]];
    [self.tabBarController.view addSubview:_toolbar];
    
    _deleteItems = [[NSMutableArray alloc] init];
}

- (void)showSign
{
    //判断是否登录
    if ([[BJUserStatus sharedStatus] isLogined]) {
        
    }else
    {
        [[BJUserStatus sharedStatus] showLoginFromViewController:self];
    }
}

-(void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
    [self.view resignFirstResponder];
    [self.navigationController.view resignFirstResponder];
}

- (void)deleteBtn:(UIButton *)button
{
    for (id item in _deleteItems) {
        [_dataList removeObject:item];
    }
    [_collectionView reloadData];
    [self saveData];
}

//取消
- (void)cancelBtn:(UIButton *)button
{
    [self.toolbar setHidden:YES];
    _isEditing = NO;
    [_collectionView reloadData];
    [_collectionView addGestureRecognizer:longPress];
    [self saveData];
}

- (void)changeState:(UILongPressGestureRecognizer *)press{
    _isEditing = YES;
    [_collectionView reloadData];
    [_collectionView removeGestureRecognizer:press];
    [self homeContentViewDidBeginEditing];
}

#pragma mark - contentView delegate
- (void)homeContentViewDidBeginEditing{
    if (_isEditing == YES) {
        [_toolbar setHidden:NO];
    }
    if (_isEditing == NO) {
        [_toolbar setHidden:YES];
        self.tabBarController.tabBar.hidden = NO;
    }
}


#pragma mark -
//头视图
- (UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath
{
    NSString *spath = [[NSBundle mainBundle] pathForResource:@"SliderImage" ofType:@"plist"];
    NSArray *sliderData = [NSArray arrayWithContentsOfFile:spath];
    UICollectionReusableView *reusableView = nil;
    if (kind == UICollectionElementKindSectionHeader) {
        ScrollViewSlider *headerView = [collectionView dequeueReusableSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"headerCell" forIndexPath:indexPath];
        headerView.backgroundColor = [UIColor clearColor];
        reusableView = headerView;
        headerView.dataList =sliderData;
    }
    return reusableView;
}


- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView{
    return 1;
}

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
    return [_dataList count];
}

//每个collectionView的大小
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath{
     contentWidth = SWIDTH/3-0.01;
    return CGSizeMake(contentWidth, contentWidth);
}

//横向
- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout minimumInteritemSpacingForSectionAtIndex:(NSInteger)section{
    return 0.001;
}

//纵向
- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout minimumLineSpacingForSectionAtIndex:(NSInteger)section{
    return 0.001;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
    HomeContentViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"cellItem" forIndexPath:indexPath];
    NSDictionary *data = [_dataList objectAtIndex:[indexPath row]];
    cell.imageSize = CGSizeMake(40, 40);
    cell.data = data;
    //[self setCellVibrate:cell IndexPath:indexPath];//显示隐藏按钮
    //cell.layer.borderColor = [UIColor colorWithHexString:@"0xC7C7C7"].CGColor;
    //cell.layer.borderWidth = 0.3;
    if (_isEditing) {
        [cell.button setHidden:NO];
        [cell.button setSelected:NO];
        [cell.button setUserInteractionEnabled:YES];
        [cell.button addTarget:self action:@selector(changeSelect:) forControlEvents:UIControlEventTouchUpInside];
    }else {
        [cell.button setHidden:YES];
    }
    cell.button.tag = 100+indexPath.row;
    return cell;
}

- (BOOL)collectionView:(UICollectionView *)collectionView shouldSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
    return YES;
}

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{
    if (!_isEditing) {
        NSDictionary *dic = [_dataList objectAtIndex:indexPath.row];
        if ([[dic objectForKey:@"id"] intValue] == 0) {
            HomeAddViewController *searchView = [[HomeAddViewController alloc] init];
            searchView.addDelegate = self;
            searchView.selectedItems = _dataList;
            DSXNavigationController *nav = [[DSXNavigationController alloc] initWithRootViewController:searchView];
            [self presentViewController:nav animated:NO completion:nil];
        }
    }
}

//显示隐藏按钮 是否删除
- (void)setCellVibrate:(HomeContentViewCell *)cell IndexPath:(NSIndexPath *)indexPath{
    cell.indexPath = indexPath;
    cell.button.hidden = deleteBtnFlag?YES:NO;
}

- (void)changeSelect:(UIButton *)button{
    NSInteger i = button.tag - 100;
    id data = [_dataList objectAtIndex:i];
    if(button.isSelected){
        [button setSelected:NO];
        [_deleteItems removeObject:data];
    }else{
        [button setSelected:YES];
        [_deleteItems addObject:data];
    }
}

#pragma mark - save data
- (void)saveData{
    [[NSUserDefaults standardUserDefaults] setObject:_dataList forKey:@"menuItems"];
}

- (void)addItem:(NSDictionary *)data{
    [_dataList removeObject:_addDic];
    [_dataList addObject:data];
    [_dataList addObject:_addDic];
    [self saveData];
    [_collectionView reloadData];
}

#pragma mark - addItemDelegate
- (void)addMenuItem:(NSDictionary *)data{
    [self addItem:data];
}

@end
